using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Linq;

namespace F1RacingGame
{
    public class GamePlayScreen : IGameScreen
    {
        private Car playerCar;
        private List<Car> aiCars;
        private List<Rectangle> obstacles;
        private List<Rectangle> checkpoints;
        
        // 油量系统
        private List<Car> fuelTrucks; // 加油车列表
        private float fuelConsumptionRate = 1.0f; // 每秒消耗的油量（秒）
        private const float FUEL_REFILL_AMOUNT = 15.0f; // 加油车增加的油量（秒）
        private const float COLLISION_FUEL_PENALTY = 5.0f; // 碰撞扣减的油量（秒）
        
        // 游戏状态
        private bool isGameRunning = false;
        private bool isGamePaused = false;
        private int currentLevel = 1; // 当前关卡
        private int totalLevels = 6; // 总关卡数
        private float lapTime = 0;
        private float bestLapTime = float.MaxValue;
        private int currentCheckpoint = 0;
        private const float TOTAL_GAME_TIME = 180.0f; // 3分钟 = 180秒
        
        // 街机赛车特有属性
        private float roadSpeed = 3.0f; // 道路移动速度
        private float playerCarX = 0; // 主角车的X位置（相对于屏幕中心）
        private float playerCarY; // 主角车的Y位置（固定在底部）
        private float collisionRecoveryTime = 0; // 碰撞恢复时间
        private const float COLLISION_RECOVERY_DURATION = 0.5f; // 碰撞恢复持续时间（缩短）
        
        // 旋转碰撞系统
        private float rotationAngle = 0; // 当前旋转角度
        private float targetRotation = 0; // 目标旋转角度
        private bool isRotating = false; // 是否正在旋转
        private float rotationSpeed = 0; // 旋转速度
        private const float ROTATION_SPEED = 30.0f; // 旋转速度常量（加快）
        private const float ROTATIONS_PER_COLLISION = 3; // 每次碰撞旋转圈数
        private bool hasFuelPenaltyApplied = false; // 是否已经扣减油量（防止旋转期间重复扣减）
        
        // 敌方赛车AI参数
        private Random aiRandom = new Random();
        private Dictionary<Car, float> aiCarTimers = new Dictionary<Car, float>(); // 每个AI车的计时器
        private Dictionary<Car, float> aiCarDirections = new Dictionary<Car, float>(); // 每个AI车的移动方向
        
                 // 移动障碍物系统
         // 障碍物会从上向下移动，但不会旋转
         
         // 自动演示系统
         private bool isDemoMode = false;
         private bool hasManualDemoTriggered = false; // 用户是否手动触发过演示模式
         private float demoTimer = 0;
         private float demoActionTimer = 0;
         private const float DEMO_ACTION_INTERVAL = 0.5f; // 演示动作间隔 - 降低频率，减少晃动
         private Random demoRandom = new Random();
         
         // 演示模式状态记忆
         private float lastTargetX = 0; // 上次的目标位置
         private bool isMovingToTarget = false; // 是否正在移动到目标位置
         private float targetReachTimer = 0; // 到达目标的计时器
         
         // AI避让状态管理
         private bool isAvoidingObstacle = false; // 是否正在避让障碍物
         private bool isAvoidingCar = false; // 是否正在避让AI车
         private float avoidanceDirection = 0; // 避让方向 (-1: 左, 0: 中, 1: 右)
         private float avoidanceTimer = 0; // 避让计时器
         private const float AVOIDANCE_DURATION = 2.0f; // 避让持续时间
         
         // UI元素 - 使用静态资源避免重复创建
        private static Font hudFont;
        private static SolidBrush hudBrush;
        private static SolidBrush backgroundBrush;
        private static bool resourcesInitialized = false;
        
        // 赛道数据
        private string currentTrack = "Monza";
        
        public void Initialize()
        {
            // 初始化字体和画笔 - 8位机像素风格（只初始化一次）
            if (!resourcesInitialized)
            {
                hudFont = new Font("Courier New", 12, FontStyle.Bold); // 像素风格字体
                hudBrush = new SolidBrush(Color.FromArgb(255, 255, 255, 255)); // 白色
                backgroundBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 0)); // 黑色背景
                resourcesInitialized = true;
            }
            
            // 创建玩家赛车 - 位置在底部中央
            playerCar = new Car("Ferrari", 200, 15, 80, 100);
            playerCarY = GameEngine.GAME_HEIGHT - 80; // 固定在底部
            playerCarX = 0; // 相对于屏幕中心的位置
            playerCar.Reset(GameEngine.GAME_WIDTH / 2, playerCarY);
            
            // 创建AI赛车 - 减少数量，更稀疏分布
            aiCars = new List<Car>
            {
                new Car("Enemy1", 150, 12, 70, 80),
                new Car("Enemy2", 160, 13, 75, 85),
                new Car("Enemy3", 145, 11, 65, 75),
                new Car("Enemy4", 155, 14, 80, 90)
            };
            
            // 创建加油车（白色）- 平均分布3个
            fuelTrucks = new List<Car>();
            int fuelTruckCount = 3; // 固定3个加油车
            
            for (int i = 0; i < fuelTruckCount; i++)
            {
                Car fuelTruck = new Car("FuelTruck", 100, 8, 60, 100);
                fuelTruck.Name = "FuelTruck" + (i + 1);
                
                // 平均分布X位置，在赛道范围内
                float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                float carWidth = fuelTruck.Width;
                float maxTrackWidth = carWidth * trackWidthMultiplier;
                float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
                float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
                float trackWidth = rightBoundary - leftBoundary;
                
                // 将赛道分为4段，加油车分布在第1、2、3段（避开最右边）
                float segmentWidth = trackWidth / 4;
                float baseX = leftBoundary + segmentWidth * (i + 1);
                float x = baseX + aiRandom.Next(-20, 21); // 在段内稍微随机偏移
                
                // 限制在赛道范围内
                if (x < leftBoundary) x = leftBoundary + 10;
                if (x > rightBoundary) x = rightBoundary - 10;
                
                // 平均分布Y位置，在屏幕上方不同高度
                float y = -100 - i * 150 - aiRandom.Next(0, 100);
                
                fuelTruck.Reset(x, y);
                fuelTrucks.Add(fuelTruck);
            }
            
                         // 设置AI赛车初始位置 - 均匀分布，避免过于集中
             for (int i = 0; i < aiCars.Count; i++)
             {
                 // 均匀分布X位置，在赛道范围内
                 float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                 float carWidth = aiCars[i].Width;
                 float maxTrackWidth = carWidth * trackWidthMultiplier;
                 float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
                 float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
                 float trackWidth = rightBoundary - leftBoundary;
                 
                 // 将赛道分为5段，AI车分布在不同段
                 float segmentWidth = trackWidth / 5;
                 int segmentIndex = i % 5; // 循环使用5个段
                 float baseX = leftBoundary + segmentWidth * segmentIndex + segmentWidth / 2;
                 float x = baseX + aiRandom.Next(-30, 31); // 在段内随机偏移
                 
                 // 限制在赛道范围内
                 if (x < leftBoundary) x = leftBoundary + 15;
                 if (x > rightBoundary) x = rightBoundary - 15;
                 
                 // 均匀分布Y位置，避免重叠
                 float y = -100 - i * 120 - aiRandom.Next(0, 80); // 每个车间隔120像素，稍微随机偏移
                 
                 aiCars[i].Reset(x, y);
                 
                 // 初始化AI车的计时器和方向
                 aiCarTimers[aiCars[i]] = aiRandom.Next(0, 100) * 0.01f; // 随机初始时间
                 aiCarDirections[aiCars[i]] = aiRandom.Next(-1, 2); // 随机初始方向
             }
            
            // 创建障碍物
            CreateObstacles();
            
            // 创建检查点
            CreateCheckpoints();
            
            // 开始游戏
            isGameRunning = true;
            isGamePaused = false;
            currentLevel = 1;
            lapTime = 0;
            currentCheckpoint = 0;
            collisionRecoveryTime = 0;
            isRotating = false;
            rotationAngle = 0;
            targetRotation = 0;
            
                         // 移动障碍物系统已初始化
             
             // 初始化演示模式
             isDemoMode = false;
             demoTimer = 0;
             demoActionTimer = 0;
             lastTargetX = 0;
             isMovingToTarget = false;
             targetReachTimer = 0;
             
             // 初始化AI避让状态
             isAvoidingObstacle = false;
             isAvoidingCar = false;
             avoidanceDirection = 0;
             avoidanceTimer = 0;
         }
        
        private void CreateObstacles()
        {
            obstacles = new List<Rectangle>
            {
                // 移动障碍物 - 会从上向下移动，但不会旋转
                new Rectangle(300, 200, 40, 35),   // 第一个障碍物
                new Rectangle(250, 600, 35, 40),   // 第二个障碍物
                new Rectangle(350, 1000, 50, 30),  // 第三个障碍物
                new Rectangle(200, 1400, 45, 35),  // 第四个障碍物
                new Rectangle(400, 1800, 30, 45),  // 第五个障碍物
                new Rectangle(280, 2200, 40, 30),  // 第六个障碍物
                new Rectangle(320, 2600, 35, 40),  // 第七个障碍物
                new Rectangle(180, 3000, 50, 35),  // 第八个障碍物
                new Rectangle(420, 3400, 30, 45),  // 第九个障碍物
                new Rectangle(260, 3800, 40, 30)   // 第十个障碍物
            };
        }
        
        private void CreateCheckpoints()
        {
            checkpoints = new List<Rectangle>
            {
                // 初始检查点 - 与初始障碍物分布相匹配
                new Rectangle(0, 300, GameEngine.GAME_WIDTH, 20),
                new Rectangle(0, 700, GameEngine.GAME_WIDTH, 20),
                new Rectangle(0, 1100, GameEngine.GAME_WIDTH, 20),
                new Rectangle(0, 1500, GameEngine.GAME_WIDTH, 20),
                new Rectangle(0, 1900, GameEngine.GAME_WIDTH, 20)
            };
        }
        
        public void Update()
        {
            if (!isGameRunning || isGamePaused)
                return;
            
            // 更新碰撞恢复时间
            if (collisionRecoveryTime > 0)
            {
                collisionRecoveryTime -= 1.0f / GameEngine.FPS;
            }
            
            // 更新旋转系统
            UpdateRotation();
            
                         // 更新演示模式
             UpdateDemoMode();
             
             // 更新玩家赛车位置（街机赛车逻辑）
             UpdatePlayerCar();
            
            // 检查玩家是否碰到赛道边界
            if (IsPlayerOutOfBounds())
            {
                // 游戏失败
                GameOver();
                return;
            }
            
            // 更新AI赛车（从上向下移动）
            foreach (var aiCar in aiCars)
            {
                UpdateAICar(aiCar);
            }
            
            // 更新加油车（从上向下移动）
            foreach (var fuelTruck in fuelTrucks)
            {
                UpdateFuelTruck(fuelTruck);
            }
            
            // 移动障碍物和检查点（从上向下移动）
            MoveRoadElements();
            
            // 更新游戏时间
            lapTime += 1.0f / GameEngine.FPS;
            
            // 更新油量消耗 - 无论加速还是正常前进都消耗相同油量
            playerCar.ConsumeFuel(fuelConsumptionRate / GameEngine.FPS);
            
            // 检查油量是否耗尽
            if (playerCar.IsFuelEmpty)
            {
                GameOver();
                return;
            }
            
            // 检查是否达到5分钟时间限制
            if (lapTime >= TOTAL_GAME_TIME)
            {
                GameFinished();
                return;
            }
            
            // 移动障碍物系统 - 障碍物会移动但不会旋转
            
            // 检查碰撞
            CheckCollisions();
            
            // 检查检查点
            CheckCheckpoints();
            
            // 检查完成关卡
            CheckLevelCompletion();
            StartNextLevel(); // 确保关卡自动推进
        }
        
                 private void UpdateDemoMode()
         {
             // 如果游戏运行超过10秒没有玩家输入，且用户未手动触发过，自动进入演示模式
             if (!isDemoMode && !hasManualDemoTriggered && lapTime > 10.0f)
             {
                 isDemoMode = true;
                 demoTimer = 0;
                 demoActionTimer = 0;
             }
             
             if (isDemoMode)
             {
                 demoTimer += 1.0f / GameEngine.FPS;
                 demoActionTimer += 1.0f / GameEngine.FPS;
                 
                 // 每0.5秒执行一次演示动作
                 if (demoActionTimer >= DEMO_ACTION_INTERVAL)
                 {
                     PerformDemoAction();
                     demoActionTimer = 0;
                 }
                 
                 // 演示模式持续30秒后退出
                 if (demoTimer > 30.0f)
                 {
                     isDemoMode = false;
                     hasManualDemoTriggered = false; // 重置手动触发标志
                     demoTimer = 0;
                     demoActionTimer = 0;
                 }
             }
         }
         
         private void PerformDemoAction()
         {
             // 智能演示模式 - 带碰撞预测的避障算法
             
             Rectangle playerBounds = playerCar.GetBounds();
             float playerCenterX = playerBounds.X + playerBounds.Width / 2;
             
             // 获取赛道边界
             float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
             float carWidth = playerCar.Width;
             float maxTrackWidth = carWidth * trackWidthMultiplier;
             float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
             float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
             
             // 更新避让计时器
             avoidanceTimer += DEMO_ACTION_INTERVAL;
             
             // 如果正在避让且时间未到，继续避让动作
             if ((isAvoidingObstacle || isAvoidingCar) && avoidanceTimer < AVOIDANCE_DURATION)
             {
                 // 继续执行避让动作
                 if (avoidanceDirection < 0)
                 {
                     playerCar.IsTurningLeft = true;
                     playerCar.IsTurningRight = false;
                 }
                 else if (avoidanceDirection > 0)
                 {
                     playerCar.IsTurningLeft = false;
                     playerCar.IsTurningRight = true;
                 }
                 else
                 {
                     playerCar.IsTurningLeft = false;
                     playerCar.IsTurningRight = false;
                 }
                 return; // 继续避让，不重新计算
             }
             
             // 重置避让状态
             isAvoidingObstacle = false;
             isAvoidingCar = false;
             avoidanceDirection = 0;
             
             // 1. 碰撞预测 - 检查下一步是否会碰撞
             bool willCollideWithObstacle = false;
             bool willCollideWithCar = false;
             Rectangle collisionObstacle = new Rectangle();
             Car collisionCar = null;
             
             // 预测玩家车下一步的位置（考虑当前移动方向）
             float nextPlayerX = playerCenterX;
             if (playerCar.IsTurningLeft) nextPlayerX -= 3.0f; // 假设移动速度
             if (playerCar.IsTurningRight) nextPlayerX += 3.0f;
             
             // 检查障碍物碰撞预测
             foreach (var obstacle in obstacles)
             {
                 if (obstacle.Y > playerBounds.Y - 250 && obstacle.Y < playerBounds.Y + 50)
                 {
                     float obstacleCenterX = obstacle.X + obstacle.Width / 2;
                     float distance = Math.Abs(obstacleCenterX - nextPlayerX);
                     
                     // 如果距离小于安全距离，预测会碰撞
                     if (distance < 60) // 安全距离
                     {
                         willCollideWithObstacle = true;
                         collisionObstacle = obstacle;
                         break;
                     }
                 }
             }
             
             // 检查AI车碰撞预测
             foreach (var aiCar in aiCars)
             {
                 Rectangle aiBounds = aiCar.GetBounds();
                 if (aiBounds.Y > playerBounds.Y - 200 && aiBounds.Y < playerBounds.Y + 50)
                 {
                     float aiCenterX = aiBounds.X + aiBounds.Width / 2;
                     float distance = Math.Abs(aiCenterX - nextPlayerX);
                     
                     // 如果距离小于安全距离，预测会碰撞
                     if (distance < 50) // 安全距离
                     {
                         willCollideWithCar = true;
                         collisionCar = aiCar;
                         break;
                     }
                 }
             }
             
             // 2. 避让决策
             if (willCollideWithObstacle)
             {
                 // 紧急避让障碍物
                 float obstacleCenterX = collisionObstacle.X + collisionObstacle.Width / 2;
                 
                 // 计算障碍物左右两侧的可用空间
                 float leftSpace = obstacleCenterX - leftBoundary;
                 float rightSpace = rightBoundary - obstacleCenterX;
                 
                 // 选择空间更大的方向进行避让
                 if (leftSpace > rightSpace)
                 {
                     avoidanceDirection = -1; // 向左避让
                 }
                 else
                 {
                     avoidanceDirection = 1; // 向右避让
                 }
                 
                 isAvoidingObstacle = true;
                 avoidanceTimer = 0;
                 
                 // 紧急减速
                 roadSpeed = Math.Max(roadSpeed - 1.5f, 1.5f);
             }
             else if (willCollideWithCar)
             {
                 // 避让AI赛车
                 Rectangle aiBounds = collisionCar.GetBounds();
                 float aiCenterX = aiBounds.X + aiBounds.Width / 2;
                 
                 // 计算AI车左右两侧的可用空间
                 float leftSpace = aiCenterX - leftBoundary;
                 float rightSpace = rightBoundary - aiCenterX;
                 
                 // 选择空间更大的方向进行避让
                 if (leftSpace > rightSpace)
                 {
                     avoidanceDirection = -1; // 向左避让
                 }
                 else
                 {
                     avoidanceDirection = 1; // 向右避让
                 }
                 
                 isAvoidingCar = true;
                 avoidanceTimer = 0;
                 
                 // 适当减速
                 roadSpeed = Math.Max(roadSpeed - 0.8f, 2.0f);
             }
             else
             {
                 // 前方安全，直线行驶并加速
                 playerCar.IsTurningLeft = false;
                 playerCar.IsTurningRight = false;
                 
                 // 在安全路段主动加速
                 if (roadSpeed < 7.0f)
                 {
                     roadSpeed = Math.Min(roadSpeed + 0.3f, 7.0f);
                 }
             }
             
             // 3. 边界检查 - 确保不会开出赛道
             if (playerCenterX < leftBoundary + 30)
             {
                 // 太靠左了，向右移动
                 playerCar.IsTurningLeft = false;
                 playerCar.IsTurningRight = true;
             }
             else if (playerCenterX > rightBoundary - 30)
             {
                 // 太靠右了，向左移动
                 playerCar.IsTurningLeft = true;
                 playerCar.IsTurningRight = false;
             }
         }
         
         private float CalculateOptimalAvoidancePath(Rectangle playerBounds, Rectangle obstacle, float leftBoundary, float rightBoundary)
         {
             // 计算最佳避让路径
             float playerCenterX = playerBounds.X + playerBounds.Width / 2;
             float obstacleCenterX = obstacle.X + obstacle.Width / 2;
             
             // 计算障碍物左右两侧的可用空间
             float leftSpace = obstacleCenterX - leftBoundary;
             float rightSpace = rightBoundary - obstacleCenterX;
             
             // 计算避让距离（障碍物宽度 + 安全距离）
             float avoidanceDistance = obstacle.Width + 40;
             
             // 选择空间更大的方向进行避让
             if (leftSpace > rightSpace)
             {
                 // 向左避让
                 float targetX = obstacleCenterX - avoidanceDistance;
                 // 确保不超出左边界
                 return Math.Max(targetX, leftBoundary + 30);
             }
             else
             {
                 // 向右避让
                 float targetX = obstacleCenterX + avoidanceDistance;
                 // 确保不超出右边界
                 return Math.Min(targetX, rightBoundary - 30);
             }
         }
         
         private void UpdateRotation()
         {
             if (isRotating)
             {
                 rotationAngle += rotationSpeed;
                 playerCar.RotationAngle = rotationAngle; // 直接设置玩家车的旋转角度
                 
                 // 检查是否完成旋转
                 if (rotationAngle >= targetRotation)
                 {
                     isRotating = false;
                     rotationAngle = 0; // 重置为0度（正前方）
                     playerCar.RotationAngle = 0; // 车头恢复正前方方向
                     hasFuelPenaltyApplied = false; // 重置油量扣减标志，允许下次碰撞时扣减油量
                     // 恢复正常速度
                     roadSpeed = Math.Max(roadSpeed, 3.0f);
                 }
             }
         }
        
        private void UpdatePlayerCar()
        {
            // 街机赛车：主角车固定在底部，只能左右移动
            float moveSpeed = 3.0f;
            
            // 如果正在碰撞恢复中，减少移动速度
            if (collisionRecoveryTime > 0)
            {
                moveSpeed *= 0.5f;
            }
            
            // 处理左右移动
            if (playerCar.IsTurningLeft)
            {
                playerCarX -= moveSpeed;
            }
            if (playerCar.IsTurningRight)
            {
                playerCarX += moveSpeed;
            }
            
            // 根据关卡限制主角车的左右移动范围
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            float maxLeft = -(maxTrackWidth / 2);
            float maxRight = maxTrackWidth / 2;
            
            if (playerCarX < maxLeft) playerCarX = maxLeft;
            if (playerCarX > maxRight) playerCarX = maxRight;
            
            // 更新主角车的实际位置
            playerCar.X = GameEngine.GAME_WIDTH / 2 + playerCarX;
            playerCar.Y = playerCarY;
        }
        
        private bool IsPlayerOutOfBounds()
        {
            // 根据关卡计算赛道边界
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            
            float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
            float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
            
            return playerCar.X < leftBoundary || playerCar.X > rightBoundary;
        }
        
        private void UpdateAICar(Car aiCar)
        {
            // 街机赛车：AI车辆从上向下移动
            aiCar.Y += roadSpeed;
            
            // 更新AI车的计时器
            if (!aiCarTimers.ContainsKey(aiCar))
            {
                aiCarTimers[aiCar] = 0;
                aiCarDirections[aiCar] = 0;
            }
            
            aiCarTimers[aiCar] += 1.0f / GameEngine.FPS;
            
            // 每2-4秒改变一次移动方向
            if (aiCarTimers[aiCar] > aiRandom.Next(20, 41) * 0.1f)
            {
                aiCarDirections[aiCar] = aiRandom.Next(-1, 2); // -1: 左, 0: 中, 1: 右
                aiCarTimers[aiCar] = 0;
            }
            
            // 根据方向移动AI车
            float moveSpeed = 1.5f;
            if (aiCarDirections[aiCar] == -1)
            {
                aiCar.X -= moveSpeed;
            }
            else if (aiCarDirections[aiCar] == 1)
            {
                aiCar.X += moveSpeed;
            }
            
            // 根据关卡限制AI车在赛道范围内
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = aiCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            
            float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
            float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
            
            if (aiCar.X < leftBoundary) 
            {
                aiCar.X = leftBoundary;
                aiCarDirections[aiCar] = 1; // 碰到左边界就向右移动
            }
            if (aiCar.X > rightBoundary) 
            {
                aiCar.X = rightBoundary;
                aiCarDirections[aiCar] = -1; // 碰到右边界就向左移动
            }
            
                         // 如果AI车辆移出屏幕底部，重新放置到顶部均匀分布位置
             if (aiCar.Y > GameEngine.GAME_HEIGHT + 50)
             {
                 // 根据AI车在列表中的索引确定均匀分布位置
                 int carIndex = aiCars.IndexOf(aiCar);
                 
                 // 均匀分布X位置，在赛道范围内
                 float trackWidthMultiplier2 = GetTrackWidthMultiplier(currentLevel);
                 float carWidth2 = aiCar.Width;
                 float maxTrackWidth2 = carWidth2 * trackWidthMultiplier2;
                 float leftBoundary2 = (GameEngine.GAME_WIDTH - maxTrackWidth2) / 2;
                 float rightBoundary2 = (GameEngine.GAME_WIDTH + maxTrackWidth2) / 2;
                 float trackWidth2 = rightBoundary2 - leftBoundary2;
                 
                 // 将赛道分为5段，AI车分布在不同段
                 float segmentWidth2 = trackWidth2 / 5;
                 int segmentIndex2 = carIndex % 5; // 循环使用5个段
                 float baseX2 = leftBoundary2 + segmentWidth2 * segmentIndex2 + segmentWidth2 / 2;
                 float newX = baseX2 + aiRandom.Next(-30, 31); // 在段内随机偏移
                 
                 // 限制在赛道范围内
                 if (newX < leftBoundary2) newX = leftBoundary2 + 15;
                 if (newX > rightBoundary2) newX = rightBoundary2 - 15;
                 
                 // 均匀分布Y位置，避免重叠
                 float newY = -100 - carIndex * 120 - aiRandom.Next(0, 80);
                 
                 aiCar.Reset(newX, newY);
                 
                 // 重置AI车的计时器和方向
                 aiCarTimers[aiCar] = aiRandom.Next(0, 100) * 0.01f;
                 aiCarDirections[aiCar] = aiRandom.Next(-1, 2);
             }
        }
        
        private void UpdateFuelTruck(Car fuelTruck)
        {
            // 加油车从上向下移动，速度较慢
            fuelTruck.Y += roadSpeed * 0.8f; // 加油车移动速度稍慢
            
            // 如果加油车移出屏幕底部，重新放置到顶部平均分布位置
            if (fuelTruck.Y > GameEngine.GAME_HEIGHT + 50)
            {
                // 根据加油车编号确定平均分布位置
                int truckIndex = int.Parse(fuelTruck.Name.Replace("FuelTruck", "")) - 1;
                
                // 平均分布X位置，在赛道范围内
                float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                float carWidth = fuelTruck.Width;
                float maxTrackWidth = carWidth * trackWidthMultiplier;
                float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
                float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
                float trackWidth = rightBoundary - leftBoundary;
                
                // 将赛道分为4段，加油车分布在第1、2、3段（避开最右边）
                float segmentWidth = trackWidth / 4;
                float baseX = leftBoundary + segmentWidth * (truckIndex + 1);
                float newX = baseX + aiRandom.Next(-20, 21); // 在段内稍微随机偏移
                
                // 限制在赛道范围内
                if (newX < leftBoundary) newX = leftBoundary + 10;
                if (newX > rightBoundary) newX = rightBoundary - 10;
                
                // 平均分布Y位置，在屏幕上方不同高度
                float newY = -100 - truckIndex * 150 - aiRandom.Next(0, 100);
                
                fuelTruck.Reset(newX, newY);
            }
        }
        
        private void UpdateObstacleSpawning()
        {
            // 移动障碍物系统 - 障碍物会移动但不需要动态生成
            // 障碍物在游戏开始时创建，之后会移动但不会旋转
        }
        
        private void SpawnNewObstacle()
        {
            // 移动障碍物系统 - 障碍物会移动但不需要动态生成新障碍物
        }
        
        private void MoveRoadElements()
        {
            // 移动障碍物（从上向下移动，但不旋转）
            for (int i = 0; i < obstacles.Count; i++)
            {
                var obstacle = obstacles[i];
                obstacle.Y += (int)roadSpeed;
                obstacles[i] = obstacle;
            }
            
            // 移动检查点
            for (int i = 0; i < checkpoints.Count; i++)
            {
                var checkpoint = checkpoints[i];
                checkpoint.Y += (int)roadSpeed;
                
                // 如果检查点移出屏幕底部，重新放置到顶部
                if (checkpoint.Y > GameEngine.GAME_HEIGHT + 50)
                {
                    checkpoint.Y = -50;
                }
                
                checkpoints[i] = checkpoint;
            }
        }
        
        private void CheckCollisions()
        {
            // 检查主角赛车与加油车的碰撞 - 只有主角赛车能获取油量
            for (int i = fuelTrucks.Count - 1; i >= 0; i--)
            {
                var fuelTruck = fuelTrucks[i];
                if (playerCar.GetBounds().IntersectsWith(fuelTruck.GetBounds()))
                {
                    // 主角赛车碰到加油车，增加油量
                    playerCar.AddFuel(FUEL_REFILL_AMOUNT);
                    // 移除这个加油车
                    fuelTrucks.RemoveAt(i);
                    // 播放加油音效（如果有的话）
                    // SoundManager.Instance.PlayFuelSound();
                    return; // 只处理一次碰撞
                }
            }
            
            // 检查AI赛车与加油车的碰撞 - AI赛车不能获取油量，但会穿过加油车
            foreach (var aiCar in aiCars)
            {
                for (int i = fuelTrucks.Count - 1; i >= 0; i--)
                {
                    var fuelTruck = fuelTrucks[i];
                    if (aiCar.GetBounds().IntersectsWith(fuelTruck.GetBounds()))
                    {
                        // AI赛车碰到加油车，不获取油量，但加油车会被移除（避免AI车阻挡加油车）
                        fuelTrucks.RemoveAt(i);
                        break; // 处理完这个AI车的碰撞后继续检查其他AI车
                    }
                }
            }
            
            // 如果正在旋转，不进行碰撞检测（避免重复扣减油量）
            if (isRotating)
                return;
            
            // 检查与障碍物的碰撞 - 旋转3圈并减速，扣油量
            foreach (var obstacle in obstacles)
            {
                if (playerCar.GetBounds().IntersectsWith(obstacle))
                {
                    // 撞到障碍物，旋转3圈并减速，扣油量
                    HandleObstacleCollision();
                    // 播放碰撞音效
                    SoundManager.Instance.PlayCollisionSound();
                    return; // 只处理一次碰撞
                }
            }
            
            // 检查与AI赛车的碰撞 - 旋转3圈并减速，同时撞开，扣油量
            foreach (var aiCar in aiCars)
            {
                if (playerCar.GetBounds().IntersectsWith(aiCar.GetBounds()))
                {
                    // 与AI赛车碰撞，旋转3圈并减速，同时撞开，扣油量
                    HandleCarCollision(aiCar);
                    // 播放碰撞音效
                    SoundManager.Instance.PlayCollisionSound();
                    return; // 只处理一次碰撞
                }
            }
        }
        
        private enum CollisionType
        {
            Frontal, // 正面碰撞
            Side     // 侧面碰撞
        }
        
        private CollisionType DetermineCollisionType(Car player, Car enemy)
        {
            // 简单的碰撞类型判断
            // 如果玩家车在敌方车前方，认为是正面碰撞
            // 否则认为是侧面碰撞
            
            float playerFront = player.Y - player.Height / 2;
            float enemyFront = enemy.Y - enemy.Height / 2;
            
            if (playerFront < enemyFront + 10) // 玩家车在敌方车前方
            {
                return CollisionType.Frontal;
            }
            else
            {
                return CollisionType.Side;
            }
        }
        
        private void HandleSideCollision()
        {
            // 开始旋转
            isRotating = true;
            rotationSpeed = ROTATION_SPEED;
            targetRotation = rotationAngle + (360 * ROTATIONS_PER_COLLISION); // 旋转3圈
            
            // 减速
            roadSpeed = Math.Max(roadSpeed * 0.5f, 1.0f);
            
            // 设置碰撞恢复时间
            collisionRecoveryTime = COLLISION_RECOVERY_DURATION;
        }
        
        private void HandleObstacleCollision()
        {
            // 先扣减油量
            playerCar.ConsumeFuel(COLLISION_FUEL_PENALTY);
            
            // 开始旋转
            isRotating = true;
            rotationSpeed = ROTATION_SPEED;
            targetRotation = rotationAngle + (360 * ROTATIONS_PER_COLLISION); // 旋转3圈
            
            // 减速到正常速度
            roadSpeed = Math.Max(roadSpeed * 0.5f, 3.0f); // 最低速度设为正常速度3.0f
            
            // 设置碰撞恢复时间
            collisionRecoveryTime = COLLISION_RECOVERY_DURATION;
            
            // 标记已经扣减油量，防止旋转期间重复扣减
            hasFuelPenaltyApplied = true;
        }
        
        private void HandleCarCollision(Car aiCar)
        {
            // 先扣减油量
            playerCar.ConsumeFuel(COLLISION_FUEL_PENALTY);
            
            // 开始旋转
            isRotating = true;
            rotationSpeed = ROTATION_SPEED;
            targetRotation = rotationAngle + (360 * ROTATIONS_PER_COLLISION); // 旋转3圈
            
            // 减速到正常速度
            roadSpeed = Math.Max(roadSpeed * 0.5f, 3.0f); // 最低速度设为正常速度3.0f
            
            // 设置碰撞恢复时间
            collisionRecoveryTime = COLLISION_RECOVERY_DURATION;
            
            // 标记已经扣减油量，防止旋转期间重复扣减
            hasFuelPenaltyApplied = true;
            
            // 撞开效果：主角车和AI车分别向不同方向移动
            Random random = new Random();
            
            // 主角车被撞开
            if (random.Next(2) == 0)
            {
                playerCarX -= 40; // 向左撞开
            }
            else
            {
                playerCarX += 40; // 向右撞开
            }
            
            // AI车被撞开
            if (random.Next(2) == 0)
            {
                aiCar.X -= 30; // AI车向左撞开
            }
            else
            {
                aiCar.X += 30; // AI车向右撞开
            }
        }
        
        private void HandlePlayerCollision()
        {
            // 主角车被撞开的效果
            collisionRecoveryTime = COLLISION_RECOVERY_DURATION;
            
            // 随机向左或向右撞开
            Random random = new Random();
            if (random.Next(2) == 0)
            {
                playerCarX -= 30; // 向左撞开
            }
            else
            {
                playerCarX += 30; // 向右撞开
            }
            
            // 限制在边界内
            float maxLeft = -(GameEngine.GAME_WIDTH / 2 - 100);
            float maxRight = GameEngine.GAME_WIDTH / 2 - 100;
            if (playerCarX < maxLeft) playerCarX = maxLeft;
            if (playerCarX > maxRight) playerCarX = maxRight;
        }
        
        private void CheckCheckpoints()
        {
            if (currentCheckpoint < checkpoints.Count)
            {
                if (playerCar.GetBounds().IntersectsWith(checkpoints[currentCheckpoint]))
                {
                    currentCheckpoint++;
                    // 播放检查点音效
                    SoundManager.Instance.PlayCheckpointSound();
                }
            }
        }
        
        private void CheckLevelCompletion()
        {
            // 基于时间的游戏，不再基于检查点完成关卡
            // 关卡进度基于时间自动推进
            int expectedLevel = (int)(lapTime / (TOTAL_GAME_TIME / totalLevels)) + 1;
            if (expectedLevel != currentLevel && expectedLevel <= totalLevels)
            {
                currentLevel = expectedLevel;
                // 可以在这里添加关卡切换效果
            }
        }
        
        private void StartNextLevel()
        {
            // 基于时间的游戏，关卡自动推进
            // 根据当前时间计算应该在第几关
            int expectedLevel = (int)(lapTime / (TOTAL_GAME_TIME / totalLevels)) + 1;
            if (expectedLevel != currentLevel && expectedLevel <= totalLevels)
            {
                currentLevel = expectedLevel;
                
                // 根据关卡调整赛道宽度和游戏难度
                float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                
                // 重新设置AI赛车位置 - 均匀分布
                for (int i = 0; i < aiCars.Count; i++)
                {
                    // 均匀分布X位置，在赛道范围内
                    float aiTrackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                    float carWidth = aiCars[i].Width;
                    float maxTrackWidth = carWidth * aiTrackWidthMultiplier;
                    float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
                    float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
                    float trackWidth = rightBoundary - leftBoundary;
                    
                    // 将赛道分为5段，AI车分布在不同段
                    float segmentWidth = trackWidth / 5;
                    int segmentIndex = i % 5; // 循环使用5个段
                    float baseX = leftBoundary + segmentWidth * segmentIndex + segmentWidth / 2;
                    float x = baseX + aiRandom.Next(-30, 31); // 在段内随机偏移
                    
                    // 限制在赛道范围内
                    if (x < leftBoundary) x = leftBoundary + 15;
                    if (x > rightBoundary) x = rightBoundary - 15;
                    
                    // 均匀分布Y位置，避免重叠
                    float y = -150 - i * 120 - aiRandom.Next(0, 80);
                    
                    aiCars[i].Reset(x, y);
                    
                    // 重置AI车的计时器和方向
                    aiCarTimers[aiCars[i]] = aiRandom.Next(0, 100) * 0.01f;
                    aiCarDirections[aiCars[i]] = aiRandom.Next(-1, 2);
                }
                
                // 重新生成加油车 - 平均分布
                fuelTrucks.Clear();
                int fuelTruckCount = 3; // 固定3个加油车
                
                for (int i = 0; i < fuelTruckCount; i++)
                {
                    Car fuelTruck = new Car("FuelTruck", 100, 8, 60, 100);
                    fuelTruck.Name = "FuelTruck" + (i + 1);
                    
                    // 平均分布X位置，在赛道范围内
                    float fuelTrackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
                    float carWidth = fuelTruck.Width;
                    float maxTrackWidth = carWidth * fuelTrackWidthMultiplier;
                    float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
                    float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
                    float trackWidth = rightBoundary - leftBoundary;
                    
                    // 将赛道分为4段，加油车分布在第1、2、3段（避开最右边）
                    float segmentWidth = trackWidth / 4;
                    float baseX = leftBoundary + segmentWidth * (i + 1);
                    float x = baseX + aiRandom.Next(-20, 21); // 在段内稍微随机偏移
                    
                    // 限制在赛道范围内
                    if (x < leftBoundary) x = leftBoundary + 10;
                    if (x > rightBoundary) x = rightBoundary - 10;
                    
                    // 平均分布Y位置，在屏幕上方不同高度
                    float y = -100 - i * 150 - aiRandom.Next(0, 100);
                    
                    fuelTruck.Reset(x, y);
                    fuelTrucks.Add(fuelTruck);
                }
                
                // 障碍物会移动但不会旋转，不重新创建
                
                // 重新创建检查点
                CreateCheckpoints();
                
                // 重置玩家车位置
                playerCarX = 0;
                playerCar.Reset(GameEngine.GAME_WIDTH / 2, playerCarY);
                
                // 增加游戏速度
                roadSpeed = Math.Min(roadSpeed + 0.5f, 8.0f);
            }
        }
        
        private float GetTrackWidthMultiplier(int level)
        {
            // 根据关卡返回赛道宽度倍数
            switch (level)
            {
                case 1: return 6.0f; // 6辆车宽度
                case 2: return 5.0f; // 5辆车宽度
                case 3: return 4.0f; // 4辆车宽度
                case 4: return 3.0f; // 3辆车宽度
                case 5: return 2.0f; // 2辆车宽度
                case 6: return 1.0f; // 1辆车宽度
                default: return 3.0f;
            }
        }
        
        private void GameOver()
        {
            isGameRunning = false;
            float totalTime = lapTime + (currentLevel - 1) * bestLapTime;
            
            // 保存成绩到排行榜
            Leaderboard.Instance.AddEntry("Player", totalTime, playerCar.Name, currentTrack);
            
            // 显示游戏结束屏幕
            ShowGameOverScreen(totalTime);
        }
        
        private void GameFinished()
        {
            isGameRunning = false;
            
            // 计算总时间（5分钟时间限制）
            float totalTime = TOTAL_GAME_TIME;
            
            // 检查是否创造新记录
            if (Leaderboard.Instance.IsNewRecord(totalTime))
            {
                // 添加到排行榜
                Leaderboard.Instance.AddEntry("Player", totalTime, playerCar.Name, currentTrack);
            }
            
            // 添加积分
            GameManager.Instance.AddScore(1000);
            
            // 显示游戏结束界面
            ShowGameOverScreen(totalTime);
        }
        
        private void ShowGameOverScreen(float totalTime)
        {
            // 简单的游戏结束显示
            // 在实际项目中，这里可以创建一个专门的游戏结束屏幕
            GameManager.Instance.ChangeState(GameState.MainMenu);
        }
        
        public void Render(Graphics graphics)
        {
            // 确保资源已初始化
            if (!resourcesInitialized)
            {
                Initialize();
            }
            
            // 设置高质量渲染
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
            
            // 绘制竖版赛道背景
            DrawVerticalTrackBackground(graphics);
            
            // 绘制赛道边界和装饰
            DrawTrackBoundaries(graphics);
            
            // 绘制赛道装饰图案
            DrawTrackDecorations(graphics);
            
            // 绘制障碍物
            DrawObstacles(graphics);
            
            // 绘制检查点
            DrawCheckpoints(graphics);
            
            // 绘制AI赛车
            foreach (var aiCar in aiCars)
            {
                aiCar.Render(graphics);
            }
            
            // 绘制加油车
            foreach (var fuelTruck in fuelTrucks)
            {
                fuelTruck.Render(graphics);
            }
            
            // 绘制玩家赛车
            playerCar.Render(graphics);
            
            // 在演示模式下绘制AI检测显示
            if (isDemoMode)
            {
                DrawAIDetectionDisplay(graphics);
            }
            
            // 绘制左侧进度条
            DrawProgressBar(graphics);
            
            // 绘制右侧信息显示区
            DrawInfoPanel(graphics);
            
            // 绘制暂停界面
            if (isGamePaused)
            {
                DrawPauseScreen(graphics);
            }
        }
        
        // 静态资源池 - 8位机像素风格
        private static readonly SolidBrush trackBrush = new SolidBrush(Color.FromArgb(255, 128, 128, 128)); // 灰色赛道
        private static readonly SolidBrush guardRailBrush = new SolidBrush(Color.FromArgb(255, 0, 128, 0)); // 绿色护栏
        private static readonly Pen boundaryPen = new Pen(Color.FromArgb(255, 255, 255, 255), 2); // 白色边界
        private static readonly Pen lanePen = new Pen(Color.FromArgb(255, 255, 255, 255), 1); // 白色车道线
        private static readonly SolidBrush patternBrush = new SolidBrush(Color.FromArgb(255, 0, 255, 0)); // 蓝绿色小花
        private static readonly SolidBrush flagBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0)); // 红色旗帜
        private static readonly SolidBrush obstacleBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 0)); // 黑色障碍物
        private static readonly SolidBrush panelBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 0)); // 黑色面板
        private static readonly Pen panelPen = new Pen(Color.FromArgb(255, 255, 255, 255), 1); // 白色边框
        private static readonly SolidBrush redBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0)); // 红色文字
        private static readonly SolidBrush carBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0)); // 红色备用车
        private static readonly SolidBrush startBrush = new SolidBrush(Color.FromArgb(255, 255, 255, 0)); // 黄色开始牌
        private static readonly Font startFont = new Font("Courier New", 10, FontStyle.Bold); // 像素字体
        private static readonly SolidBrush blackBrush = new SolidBrush(Color.Black); // 黑色文字
        private static readonly SolidBrush yellowBrush = new SolidBrush(Color.FromArgb(255, 255, 255, 0)); // 黄色检查点
        private static readonly SolidBrush grayBrush = new SolidBrush(Color.FromArgb(255, 128, 128, 128)); // 灰色检查点
        private static readonly SolidBrush stoneTextureBrush = new SolidBrush(Color.FromArgb(255, 40, 40, 40)); // 石头纹理
        private static readonly SolidBrush stoneHighlightBrush = new SolidBrush(Color.FromArgb(255, 80, 80, 80)); // 石头高光
        
        // AI检测显示相关
        private static readonly Pen aiDetectionPen = new Pen(Color.FromArgb(255, 255, 0, 0), 2); // 红色虚框
        private static readonly Pen aiTargetPen = new Pen(Color.FromArgb(255, 0, 255, 0), 2); // 绿色目标线
        
        static GamePlayScreen()
        {
            // 设置虚线样式
            aiDetectionPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
            aiTargetPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
        }
        
        private void DrawVerticalTrackBackground(Graphics graphics)
        {
            // 根据关卡计算赛道宽度
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            
            int trackWidth = (int)maxTrackWidth;
            int trackX = (int)((GameEngine.GAME_WIDTH - trackWidth) / 2);
            
            // 绘制灰色赛道主体
            graphics.FillRectangle(trackBrush, trackX, 0, trackWidth, GameEngine.GAME_HEIGHT);
            
            // 绘制左右两侧绿色护栏区域
            graphics.FillRectangle(guardRailBrush, 0, 0, trackX, GameEngine.GAME_HEIGHT); // 左侧
            graphics.FillRectangle(guardRailBrush, trackX + trackWidth, 0, GameEngine.GAME_WIDTH - (trackX + trackWidth), GameEngine.GAME_HEIGHT); // 右侧
        }
        
        private void DrawTrackBoundaries(Graphics graphics)
        {
            // 根据关卡计算赛道宽度
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            
            int trackWidth = (int)maxTrackWidth;
            int trackX = (int)((GameEngine.GAME_WIDTH - trackWidth) / 2);
            
            // 绘制赛道边界线 - 白色像素边界
            graphics.DrawLine(boundaryPen, trackX, 0, trackX, GameEngine.GAME_HEIGHT); // 左边界
            graphics.DrawLine(boundaryPen, trackX + trackWidth, 0, trackX + trackWidth, GameEngine.GAME_HEIGHT); // 右边界
            
            // 根据关卡绘制车道分隔线
            int numLanes = (int)trackWidthMultiplier;
            for (int i = 1; i < numLanes; i++)
            {
                int laneX = trackX + (trackWidth * i) / numLanes;
                
                // 像素风格虚线车道分隔线
                for (int y = 0; y < GameEngine.GAME_HEIGHT; y += 16)
                {
                    graphics.DrawLine(lanePen, laneX, y, laneX, y + 8);
                }
            }
        }
        
        private void DrawTrackDecorations(Graphics graphics)
        {
            // 根据关卡计算赛道宽度
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            
            int trackWidth = (int)maxTrackWidth;
            int trackX = (int)((GameEngine.GAME_WIDTH - trackWidth) / 2);
            
            // 绘制左侧绿色背景的重复像素图案 - 蓝绿色小花
            for (int y = 0; y < GameEngine.GAME_HEIGHT; y += 16)
            {
                for (int x = 16; x < trackX - 16; x += 20)
                {
                    // 绘制像素风格小花图案
                    graphics.FillRectangle(patternBrush, x, y, 4, 4);
                    graphics.FillRectangle(patternBrush, x + 2, y + 2, 2, 2);
                }
            }
            
            // 绘制右侧绿色背景的重复像素图案 - 蓝绿色小花
            for (int y = 0; y < GameEngine.GAME_HEIGHT; y += 16)
            {
                for (int x = trackX + trackWidth + 16; x < GameEngine.GAME_WIDTH - 16; x += 20)
                {
                    // 绘制像素风格小花图案
                    graphics.FillRectangle(patternBrush, x, y, 4, 4);
                    graphics.FillRectangle(patternBrush, x + 2, y + 2, 2, 2);
                }
            }
            
            // 绘制左侧旗帜装饰 - 红色像素旗帜
            graphics.FillRectangle(flagBrush, 8, 8, 16, 12);
            graphics.FillRectangle(flagBrush, 6, 20, 3, 24); // 旗杆
        }
        
        private void DrawObstacles(Graphics graphics)
        {
            foreach (var obstacle in obstacles)
            {
                // 绘制不规则的黑色障碍物（类似油渍或坑洞）
                DrawIrregularObstacle(graphics, obstacle);
            }
        }
        
        private void DrawIrregularObstacle(Graphics graphics, Rectangle bounds)
        {
            // 创建石头形状的黑色障碍物 - 完全静态，不旋转
            Random random = new Random(bounds.GetHashCode()); // 使用固定种子确保每次绘制相同
            
            // 绘制简单的椭圆形石头，不旋转
            graphics.FillEllipse(obstacleBrush, bounds);
            
            // 添加石头的纹理细节（深灰色）
            for (int i = 0; i < 4; i++)
            {
                int detailX = bounds.X + random.Next(2, bounds.Width - 4);
                int detailY = bounds.Y + random.Next(2, bounds.Height - 4);
                int detailSize = random.Next(2, 5);
                
                graphics.FillEllipse(stoneTextureBrush, detailX, detailY, detailSize, detailSize);
            }
            
            // 添加石头的边缘高光（浅灰色）
            for (int i = 0; i < 3; i++)
            {
                int detailX = bounds.X + random.Next(1, bounds.Width - 2);
                int detailY = bounds.Y + random.Next(1, bounds.Height - 2);
                
                graphics.FillRectangle(stoneHighlightBrush, detailX, detailY, 1, 1);
            }
        }
        
        private void DrawCheckpoints(Graphics graphics)
        {
            for (int i = 0; i < checkpoints.Count; i++)
            {
                // 使用静态资源，避免重复创建
                SolidBrush checkpointBrush = (i == currentCheckpoint) ? yellowBrush : grayBrush;
                graphics.FillRectangle(checkpointBrush, checkpoints[i]);
            }
        }
        
        private void DrawInfoPanel(Graphics graphics)
        {
            // 右侧信息显示区 - 占据界面右侧1/4-1/3宽度
            int infoPanelWidth = (int)(GameEngine.GAME_WIDTH * 0.25f);
            int infoPanelX = GameEngine.GAME_WIDTH - infoPanelWidth;
            
            // 绘制黑色背景面板
            graphics.FillRectangle(panelBrush, infoPanelX, 0, infoPanelWidth, GameEngine.GAME_HEIGHT);
            
            // 绘制面板边框
            graphics.DrawRectangle(panelPen, infoPanelX, 0, infoPanelWidth, GameEngine.GAME_HEIGHT);
            
            // 绘制信息内容
            int startY = 50;
            int lineHeight = 40;
            
            // 关卡信息
            string levelText = "关 卡";
            graphics.DrawString(levelText, hudFont, hudBrush, infoPanelX + 20, startY);
            string levelValue = currentLevel.ToString() + "/" + totalLevels.ToString();
            graphics.DrawString(levelValue, hudFont, redBrush, infoPanelX + 20, startY + 20);
            
            // 速度信息
            startY += lineHeight * 2;
            string speedText = "速 度";
            graphics.DrawString(speedText, hudFont, hudBrush, infoPanelX + 20, startY);
            string speedValue = ((int)roadSpeed).ToString();
            graphics.DrawString(speedValue, hudFont, hudBrush, infoPanelX + 20, startY + 20);
            
            // 剩余时间信息
            startY += lineHeight * 2;
            string timeText = "剩余时间";
            graphics.DrawString(timeText, hudFont, hudBrush, infoPanelX + 20, startY);
            float remainingTime = TOTAL_GAME_TIME - lapTime;
            string timeValue = ((int)remainingTime).ToString() + "秒";
            graphics.DrawString(timeValue, hudFont, hudBrush, infoPanelX + 20, startY + 20);
            
            // 油量信息
            startY += lineHeight * 2;
            string fuelText = "油 量";
            graphics.DrawString(fuelText, hudFont, hudBrush, infoPanelX + 20, startY);
            string fuelValue = ((int)playerCar.Fuel).ToString() + "秒";
            
            // 根据油量显示不同颜色
            SolidBrush fuelBrush;
            if (playerCar.Fuel > 30)
            {
                fuelBrush = hudBrush; // 白色 - 油量充足
            }
            else if (playerCar.Fuel > 10)
            {
                fuelBrush = yellowBrush; // 黄色 - 油量警告
            }
            else
            {
                fuelBrush = redBrush; // 红色 - 油量危险
            }
            
            graphics.DrawString(fuelValue, hudFont, fuelBrush, infoPanelX + 20, startY + 20);
            
            // 演示模式说明
            startY += lineHeight * 2;
            string demoText = "智能演示模式";
            graphics.DrawString(demoText, hudFont, hudBrush, infoPanelX + 20, startY);
            string demoInstruction = "按F键激活";
            graphics.DrawString(demoInstruction, hudFont, yellowBrush, infoPanelX + 20, startY + 20);
            string demoFeature = "自动避障和超车";
            graphics.DrawString(demoFeature, hudFont, yellowBrush, infoPanelX + 20, startY + 40);
            
            // 绘制备用车辆显示（左下角小红车）- 像素风格
            graphics.FillRectangle(carBrush, 16, GameEngine.GAME_HEIGHT - 48, 16, 24);
            graphics.DrawRectangle(panelPen, 16, GameEngine.GAME_HEIGHT - 48, 16, 24);
            
                         // 绘制关卡标识 - 像素风格
             graphics.FillRectangle(startBrush, GameEngine.GAME_WIDTH / 2 - 24, 16, 48, 16);
             graphics.DrawString("第" + currentLevel.ToString() + "关", startFont, blackBrush, GameEngine.GAME_WIDTH / 2 - 30, 18);
             
             // 绘制演示模式标识
             if (isDemoMode)
             {
                 graphics.FillRectangle(yellowBrush, GameEngine.GAME_WIDTH / 2 - 50, GameEngine.GAME_HEIGHT - 40, 100, 20);
                 graphics.DrawString("智能演示模式", startFont, blackBrush, GameEngine.GAME_WIDTH / 2 - 45, GameEngine.GAME_HEIGHT - 38);
             }
        }
        
        private void DrawProgressBar(Graphics graphics)
        {
            // 左侧进度条 - 显示赛程进度
            int progressBarWidth = 20;
            int progressBarHeight = GameEngine.GAME_HEIGHT - 100;
            int progressBarX = 20;
            int progressBarY = 50;
            
            // 绘制进度条背景（深灰色）
            SolidBrush progressBackgroundBrush = new SolidBrush(Color.FromArgb(255, 64, 64, 64));
            graphics.FillRectangle(progressBackgroundBrush, progressBarX, progressBarY, progressBarWidth, progressBarHeight);
            
            // 计算当前进度百分比
            float progressPercentage = lapTime / TOTAL_GAME_TIME;
            int currentProgressHeight = (int)(progressBarHeight * progressPercentage);
            
            // 绘制进度条填充（绿色到红色的渐变）
            Color progressColor;
            if (progressPercentage < 0.5f)
            {
                // 绿色到黄色
                int green = 255;
                int red = (int)(255 * (progressPercentage * 2));
                progressColor = Color.FromArgb(255, red, green, 0);
            }
            else
            {
                // 黄色到红色
                int red = 255;
                int green = (int)(255 * (1.0f - (progressPercentage - 0.5f) * 2));
                progressColor = Color.FromArgb(255, red, green, 0);
            }
            
            SolidBrush progressFillBrush = new SolidBrush(progressColor);
            int fillY = progressBarY + progressBarHeight - currentProgressHeight;
            graphics.FillRectangle(progressFillBrush, progressBarX, fillY, progressBarWidth, currentProgressHeight);
            
            // 绘制进度条边框
            graphics.DrawRectangle(panelPen, progressBarX, progressBarY, progressBarWidth, progressBarHeight);
            
            // 绘制进度百分比文字
            string progressText = ((int)(progressPercentage * 100)).ToString() + "%";
            Font progressFont = new Font("Courier New", 10, FontStyle.Bold);
            SizeF textSize = graphics.MeasureString(progressText, progressFont);
            float textX = progressBarX + (progressBarWidth - textSize.Width) / 2;
            float textY = progressBarY + progressBarHeight + 10;
            graphics.DrawString(progressText, progressFont, hudBrush, textX, textY);
            
            // 绘制进度条标题
            string titleText = "赛程进度";
            Font titleFont = new Font("Courier New", 8, FontStyle.Bold);
            SizeF titleSize = graphics.MeasureString(titleText, titleFont);
            float titleX = progressBarX + (progressBarWidth - titleSize.Width) / 2;
            float titleY = progressBarY - 20;
            graphics.DrawString(titleText, titleFont, hudBrush, titleX, titleY);
            
            // 清理资源
            progressBackgroundBrush.Dispose();
            progressFillBrush.Dispose();
            progressFont.Dispose();
            titleFont.Dispose();
        }
        
        private void DrawAIDetectionDisplay(Graphics graphics)
        {
            // 绘制AI检测到的障碍物和赛车
            Rectangle playerBounds = playerCar.GetBounds();
            float playerCenterX = playerBounds.X + playerBounds.Width / 2;
            
            // 获取赛道边界
            float trackWidthMultiplier = GetTrackWidthMultiplier(currentLevel);
            float carWidth = playerCar.Width;
            float maxTrackWidth = carWidth * trackWidthMultiplier;
            float leftBoundary = (GameEngine.GAME_WIDTH - maxTrackWidth) / 2;
            float rightBoundary = (GameEngine.GAME_WIDTH + maxTrackWidth) / 2;
            
                         // 1. 绘制检测到的障碍物
             foreach (var obstacle in obstacles)
             {
                 // 检查障碍物是否在AI检测范围内
                 if (obstacle.Y > playerBounds.Y - 300 && obstacle.Y < playerBounds.Y + 50)
                 {
                     float obstacleCenterX = obstacle.X + obstacle.Width / 2;
                     float distance = Math.Abs(obstacleCenterX - playerCenterX);
                     
                     if (distance < 200) // AI检测距离
                     {
                         // 绘制红色虚框
                         graphics.DrawRectangle(aiDetectionPen, obstacle);
                         
                         // 绘制检测距离指示线
                         graphics.DrawLine(aiDetectionPen, 
                             playerCenterX, playerBounds.Y, 
                             obstacleCenterX, obstacle.Y + obstacle.Height / 2);
                     }
                 }
             }
             
             // 2. 绘制检测到的AI赛车
             foreach (var aiCar in aiCars)
             {
                 Rectangle aiBounds = aiCar.GetBounds();
                 // 检查AI车是否在检测范围内
                 if (aiBounds.Y > playerBounds.Y - 200 && aiBounds.Y < playerBounds.Y + 50)
                 {
                     float aiCenterX = aiBounds.X + aiBounds.Width / 2;
                     float distance = Math.Abs(aiCenterX - playerCenterX);
                     
                     if (distance < 150) // AI检测距离
                     {
                         // 绘制红色虚框
                         graphics.DrawRectangle(aiDetectionPen, aiBounds);
                         
                         // 绘制检测距离指示线
                         graphics.DrawLine(aiDetectionPen, 
                             playerCenterX, playerBounds.Y, 
                             aiCenterX, aiBounds.Y + aiBounds.Height / 2);
                     }
                 }
             }
            
            // 3. 绘制当前目标位置（如果正在移动）
            if (isMovingToTarget)
            {
                // 绘制绿色目标线
                graphics.DrawLine(aiTargetPen, 
                    playerCenterX, playerBounds.Y, 
                    lastTargetX, playerBounds.Y - 50);
                
                // 绘制目标点
                graphics.FillEllipse(new SolidBrush(Color.Green), 
                    lastTargetX - 5, playerBounds.Y - 55, 10, 10);
            }
            
                         // 4. 绘制检测范围指示
             // 障碍物检测范围（300像素）
             graphics.DrawEllipse(aiDetectionPen, 
                 playerCenterX - 300, playerBounds.Y - 300, 600, 300);
             
             // AI车检测范围（200像素）
             graphics.DrawEllipse(aiDetectionPen, 
                 playerCenterX - 200, playerBounds.Y - 200, 400, 200);
        }
        
        private void DrawPauseScreen(Graphics graphics)
        {
            // 半透明背景
            SolidBrush pauseBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 0));
            graphics.FillRectangle(pauseBrush, 0, 0, GameEngine.GAME_WIDTH, GameEngine.GAME_HEIGHT);
            
            // 暂停文本
            Font pauseFont = new Font("Arial", 24, FontStyle.Bold);
            string pauseText = "游戏暂停";
            SizeF pauseSize = graphics.MeasureString(pauseText, pauseFont);
            float pauseX = (GameEngine.GAME_WIDTH - pauseSize.Width) / 2;
            graphics.DrawString(pauseText, pauseFont, hudBrush, pauseX, GameEngine.GAME_HEIGHT / 2);
            
            pauseFont.Dispose();
            pauseBrush.Dispose();
        }
        
                 public void OnKeyDown(KeyEventArgs e)
         {
             if (!isGameRunning)
                 return;
             
             // 任何按键都会退出演示模式
             if (isDemoMode)
             {
                 isDemoMode = false;
                 hasManualDemoTriggered = false; // 重置手动触发标志
                 demoTimer = 0;
                 demoActionTimer = 0;
                 // 重置玩家车状态
                 playerCar.IsTurningLeft = false;
                 playerCar.IsTurningRight = false;
             }
                 
             switch (e.KeyCode)
            {
                case Keys.Up:
                case Keys.W:
                    // 街机赛车：上键可以增加道路速度
                    roadSpeed = Math.Min(roadSpeed + 0.5f, 8.0f);
                    break;
                case Keys.Down:
                case Keys.S:
                    // 街机赛车：下键可以减少道路速度
                    roadSpeed = Math.Max(roadSpeed - 0.5f, 1.0f);
                    break;
                case Keys.Left:
                case Keys.A:
                    playerCar.IsTurningLeft = true;
                    break;
                case Keys.Right:
                case Keys.D:
                    playerCar.IsTurningRight = true;
                    break;
                case Keys.P:
                    isGamePaused = !isGamePaused;
                    break;
                case Keys.F:
                    // 手动激活演示模式
                    if (!isDemoMode)
                    {
                        isDemoMode = true;
                        hasManualDemoTriggered = true; // 标记用户已手动触发
                        demoTimer = 0;
                        demoActionTimer = 0;
                    }
                    break;
                case Keys.Escape:
                    GameManager.Instance.ChangeState(GameState.MainMenu);
                    break;
            }
        }
        
        public void OnKeyUp(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Left:
                case Keys.A:
                    playerCar.IsTurningLeft = false;
                    break;
                case Keys.Right:
                case Keys.D:
                    playerCar.IsTurningRight = false;
                    break;
            }
        }
        
        public void Dispose()
        {
            hudFont?.Dispose();
            hudBrush?.Dispose();
            backgroundBrush?.Dispose();
        }
    }
} 